package com.roy.KafkaTest;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class PollConsumer {

//	private static final String BOOTSTRAP_SERVERS = "172.16.48.10:9092,172.16.48.11:9092,172.16.48.12:9092";
//	private static final String TOPIC = "topic1";
	
	private static final String BOOTSTRAP_SERVERS = "172.16.48.50:9092,172.16.48.51:9092,172.16.48.52:9092,172.16.48.53:9092";
	private static final String TOPIC = "log-lemon-txnplte";
	
	public static void main(String[] args) {
		Properties props = new Properties();
        /** kafka集群ip **/
        props.put("bootstrap.servers", BOOTSTRAP_SERVERS);

        /** 由于kafka有消费组的概念,每个消费者要制定一个group **/
        props.put("group.id", "test");

        /** 我们这里使用kafka high level模式，自动提交offset**/

        /** 自动提交的时间间隔 **/
        props.put("auto.commit.interval.ms", "1000");
        /** 一次最大拉取记录数 **/
        props.put("max.poll.records", 10);

        /** 制定key合value的序列化方式,这里制定的是kafka的字符串序列化 **/
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        //为了能一直重跑，这里设置为不自动提交offset并且每次从最早的记录读取。
        props.put("enable.auto.commit", "false");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        
        Consumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList(TOPIC));
        while (true) {
        	// 100毫秒超时时间
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofNanos(100));
            for (ConsumerRecord<String, String> record : records) {
            	System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            	String messageInfo = JSON.parseObject(record.value()).getString("message");
            	messageInfo = messageInfo.substring(messageInfo.indexOf("{"));
            	JSONObject jRes = JSON.parseObject(messageInfo);
            	System.out.println("jres = "+jRes.toJSONString());
            }
            
        }
	}
}
